package com.zhai.domain.credit.service;

import com.zhai.domain.credit.model.aggregate.TradeAggregate;
import com.zhai.domain.credit.model.entity.CreditAccountEntity;
import com.zhai.domain.credit.model.entity.CreditOrderEntity;
import com.zhai.domain.credit.model.entity.TradeEntity;
import com.zhai.domain.credit.repository.ICreditRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Description:
 * @ClassName: CreditAdjustService
 * @Author: zhaiyongxin
 * @Date: 2025/6/23 17:17
 * @Version: 1.0
 */
@Service
@Slf4j
public class CreditAdjustService implements ICreditAdjustService {

    @Resource
    private ICreditRepository creditRepository;

    /**
     * 创建增加积分额度订单
     *
     * @param tradeEntity
     */
    @Override
    public String createOrder(TradeEntity tradeEntity) {
        log.info("增加账户积分额度开始 userId:{} tradeName:{} amount:{}", tradeEntity.getUserId(), tradeEntity.getTradeName(), tradeEntity.getAmount());
        // 1.积分调额订单
        CreditAccountEntity creditAccountEntity = TradeAggregate.buildCreditAccountEntity(tradeEntity.getUserId(), tradeEntity.getAmount());
        // 2.积分账户
        CreditOrderEntity creditOrderEntity = TradeAggregate.buildCreditOrderEntity(tradeEntity.getUserId(),
                tradeEntity.getTradeName(),
                tradeEntity.getTradeType(),
                tradeEntity.getAmount(),
                tradeEntity.getOutBusinessNo());
        // 3.组装聚合对象
        TradeAggregate tradeAggregate = TradeAggregate.builder()
                .creditAccountEntity(creditAccountEntity)
                .creditOrderEntity(creditOrderEntity)
                .userId(tradeEntity.getUserId())
                .build();

        // 4.保存聚合对象
        creditRepository.saveUserCreditTradeOrder(tradeAggregate);
        log.info("增加账户积分额度完成 userId:{} orderId:{}", tradeEntity.getUserId(), creditOrderEntity.getOrderId());

        return creditOrderEntity.getOrderId();
    }
}
